package org.jeik.controllers;

import java.io.IOException;

import javax.faces.application.Application;
import javax.faces.application.NavigationHandler;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;

import org.jeik.utils.Log;

/**
 * 
 * @author AAsha
 * 
 */
public abstract class NavigationController {

	/**
	 * 
	 * @param rule
	 */
	public static void navigate(NavigationRule rule) {
		navigate(null, rule);
	}

	/**
	 * 
	 * @param fromAction
	 * @param rule
	 */
	public static void navigate(String fromAction, NavigationRule rule) {

		FacesContext fctx = FacesContext.getCurrentInstance();
		Application application = fctx.getApplication();
		NavigationHandler navHandler = application.getNavigationHandler();
		navHandler.handleNavigation(fctx, fromAction, rule.getOutcome());

	}

	/**
	 * 
	 * Redirect customer to the page with the speciifed viewId, this would
	 * delegates under the covers immediately to
	 * HttpServletResponse#sendRedirect()
	 * 
	 */
	public static void redirectToPage(String viewUrl) {

		FacesContext facesContext = FacesContext.getCurrentInstance();
		ExternalContext externalctx = facesContext.getExternalContext();
		try {
			externalctx.redirect(viewUrl);
		} catch (IOException e) {
			Log.error(NavigationController.class, e.getMessage(), e);
		}
	}

}
